package top.lshaci.learning.oauth2.client.controller;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.nimbusds.jose.JWSObject;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * ClientController
 *
 * @author lshaci
 * @since 1.0.0
 */
@Slf4j
@RestController
public class ClientController {

    @GetMapping(value = "get")
    @PreAuthorize("hasAuthority('ROLE_ADMIN')")
    @SneakyThrows
    public Object get(Authentication authentication) {
        authentication.getCredentials();
        OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) authentication.getDetails();
        String jwtToken = details.getTokenValue();
        JWSObject jwsObject = JWSObject.parse(jwtToken);
        String payload = jwsObject.getPayload().toString();
        JSONObject jsonObject = JSONUtil.parseObj(payload);
        return jsonObject;
    }
}
